/*
 * Copyright 2014 by État de Genève (Switzerland)
 * All rights reserved.
 *
 * Author: ELCA Informatique SA
 */
define(['services/user', 'services/notifier', 'i18n'], function (user, notifier, i18n) {

    return {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var roles = ko.unwrap(valueAccessor());

            if (!roles) {
                return;
            }

            // list all roles authorized for this element
            var rolesArr = roles.split(';');

            // find roles in common with current user
            var common = _.intersection(rolesArr, user.roles);

            if (!common || common.length === 0) {
                // disable element
                //$(element).attr('disabled', true);
                // disable click events (in case of disable above didn't work) and add an error message
                $(element).off('click').click(function (evt) {
                    notifier.error(new Error(i18n.t('cms:error.unauthorized')));
                    evt.stopPropagation();
                    return false;
                });
            }
        }
    };
});